package com.aispeech.astools.utils;

/**
 * @author rain  08.14 2018
 */

import android.media.AudioRecord;
import android.util.Log;

/**
 * Util to get record device.
 */
public class AudioRecordUtils {

    private final static String TAG = "AudioRecordUtils";

    private static int calc_buffer_size(AudioRecordConfig config) {

        int bufferSize = getReadByteBufferSize(config);
        int minBufferSize = AudioRecord.getMinBufferSize(config.getSample(), config.getChannel(),
            config.getEncoding());
        Log.d(TAG, "[bufferSize = " + bufferSize + " MinBufferSize = " + minBufferSize + "]");

        if (minBufferSize > bufferSize) {
            return minBufferSize * 4;
        }

        return bufferSize * 10;
    }

    public static int getReadByteBufferSize(AudioRecordConfig config) {
        // 1000 : s->ms , 8 : bit->byte | 16: bit->short
        Log.d(TAG, "getReadByteBufferSize with: config = " + config.toString() + "");
        int read_buffer_size = config.getSample() * config.getEncodingVal() * config.getChannelVal() * config.getReadBufIntervalTime() / (1000 * 8);
        Log.d(TAG, "[getReadByteBufferSize = " + read_buffer_size + "]");
        return read_buffer_size;
    }

    /**
     * 根据默认配置初始化一个AudioRecord对象
     *
     * @return AudioRecord 成功初始化录音设备 null 如果无法获取录音设备
     */
    public static AudioRecord newInstance(AudioRecordConfig config)
        throws IllegalArgumentException {
        Log.d(TAG, "newInstance with: config = " + config.toString() + "");

        Integer buffer_size = calc_buffer_size(config);
        Log.d(TAG, "newInstance new AudioRecord");

        AudioRecord audioRecord = new AudioRecord(config.getSource(), config.getSample(), config.getChannel(), config.getEncoding(), buffer_size);
        Log.d(TAG, "recorder.new() end");
        if (audioRecord.getState() == AudioRecord.STATE_INITIALIZED) {
            return audioRecord;
        }
        return null;
    }
}
